package sky.cin.framework.log;

import java.text.SimpleDateFormat;
import java.util.*;

public class Croog {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

    private static final Map<String, Status> limits = new HashMap<>();

    private String format;

    private String pkg;

    public Croog() {

    }

    public Croog(String packageName) {
        setPackage(packageName);
    }

    public Croog(String packageName, int packageLength) {
        setPackage(packageName, packageLength);
    }

    public static void putLimit(String pkg, String level) {
        limits.put(pkg, Status.valueOf(level));
    }

    public void setPackage(String pkg) {
        setPackage(pkg, 50);
    }

    public void setPackage(String pkg, int packageLength) {
        this.pkg = pkg;
        String len = "%-" + packageLength + "s";
        String pkgStr = String.format(len, zipName(pkg, packageLength));
        // %时间 [%等级] [包路径]: %信息
        this.format = "%s [%-5s] [" + pkgStr + "]: %s";
    }

    private String zipName(String packageName, int packageLength) {
        if (packageName.length() < packageLength) {
            return packageName;
        }
        String[] packages = packageName.split("\\.");
        for (String _pkg_ : packages) {
            char zipedPkg = _pkg_.toCharArray()[0];
            packageName = packageName.replaceFirst(_pkg_, String.valueOf(zipedPkg));
            if (packageName.length() < packageLength) {
                return packageName;
            }
        }
        return packageName;
    }

    public void info(String msg) {
        Status limit = limits.get(pkg);
        if (limit == null || limit == Status.INFO)  {
            String log = String.format(format, generateDate(), Status.INFO, msg);
            System.out.println(log);
        }
    }

    public void error(String msg) {
        Status limit = limits.get(pkg);
        if (limit == null || limit == Status.ERROR)  {
            String log = String.format(format, generateDate(), Status.ERROR, msg);
            System.err.println(log);
        }
    }

    private String generateDate() {
        return dateFormat.format(new Date(System.currentTimeMillis()));
    }

    public void info(List<Class<?>> classes) {
        String[] strings = new String[classes.size()];
        for (int index = 0; index < classes.size(); index++) {
            strings[index] = classes.get(index).getSimpleName();
        }
        info(Arrays.toString(strings));
    }

    public void info(Set<String> keySet) {
        String[] strings = new String[keySet.size()];
        int index = 0;
        for (String item : keySet) {
            strings[index++] = item;
        }
        info(Arrays.toString(strings));
    }
}
